package com.fb.common.json;

/**
 * Created by Administrator on 2018/7/3 0003.
 */
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * Created by Administrator on 2018/4/13 0013.
 */
@Slf4j
public class JsonUtil {


    ObjectMapper mapper;

    public JsonUtil()
    {
        mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        /**
         * 如果被转换对象是Object会提示
         * Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class java.lang.Object and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)
         */
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    }

    public JsonUtil(JsonInclude.Include include)
    {
        mapper = new ObjectMapper();
        mapper.setSerializationInclusion(include);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        /**
         * 如果被转换对象是Object会提示
         * Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class java.lang.Object and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)
         */
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    }


    public  String toJson(Object object)  {
        try {
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            log.error("json 格式转换错误！！，错误信息为==>{}",e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    public  <T> T fromJson(String json, Class<T> cls) throws IOException {
        return mapper.readValue(json, cls);
    }

    public  <T> T fromJson(String json,TypeReference valueTypeRef) throws IOException {
        return mapper.readValue(json, valueTypeRef);
    }

}